import {
  whilteRoutes
} from '@/router'
import {
  getPage,
  setPage,
  removePage
} from '@/utils/auth'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
// import('@/views/service/home')
// const _import = require('@/views')       //获取组件的方法
import Layout from '@/layout' //Layout 是架构组件，不在后台返回，在文件里单独引入
const page404 = {
  path: '*',
  redirect: '/404',
  hidden: true
} // 404 page must be placed at the end !!!
export function filterAsyncRouter(asyncRouterMap) { //遍历后台传来的路由字符串，转换为组件对象
  const accessedRouters = asyncRouterMap.filter(route => {


    // console.log(route,111)


    if (route.component) {
      if (route.component === 'Layout') { //Layout组件特殊处理
        route.component = Layout
      } else {
        try {
          if (require('@/views' + route.component).default) {
            route.component = require('@/views' + route.component).default
          }
        } catch (e) {
          // alert("页面获取出错")
          route.component = require('@/views/404').default
        }
        // if (require('@/views'+route.component).default) {
        //   route.component =  require('@/views/404').default
        // }
        // route.component = require('@/views'+route.component).default
      }
    }
    if (route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }
    return true
  })
  // accessedRouters.push(page404)
  return accessedRouters
}
const state = {
  routes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.routes = routes
  }
}

const actions = {
  generateRoutes({
    commit
  }, page) {
    return new Promise(resolve => {
      let accessedRoutes
      //  做假页面给page push 可以模拟页面
      
      accessedRoutes = filterAsyncRouter(page)
      accessedRoutes = accessedRoutes.concat(whilteRoutes)
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
